package com.gobang.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gobang.common.config.RabbitMQConfig;
import com.gobang.domain.dto.mq.UserRegisteredMessage;
import com.gobang.entity.PointsAccount;
import com.gobang.mapper.PointsAccountMapper;
import com.gobang.util.RedisUtil;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RequiredArgsConstructor
public class PointsEventListener {

    private final PointsAccountMapper pointsAccountMapper;

    private final RedisUtil redisUtil;

    @RabbitListener(queues = RabbitMQConfig.USER_REGISTER_QUEUE)
    public void onUserRegistered(UserRegisteredMessage message, Channel channel, Message amqpMessage) throws IOException {
        long deliveryTag = amqpMessage.getMessageProperties().getDeliveryTag();
        if (message == null || message.getUserId() == null) {
            channel.basicAck(deliveryTag, false);
            return;
        }
        Long userId = message.getUserId();
        try {
            QueryWrapper<PointsAccount> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            PointsAccount existing = pointsAccountMapper.selectOne(wrapper);
            if (existing != null) {
                channel.basicAck(deliveryTag, false);
                return;
            }
            PointsAccount account = new PointsAccount();
            account.setUserId(userId);
            account.setCurrentPoints(0);
            pointsAccountMapper.insert(account);
            redisUtil.delete("points:cache:" + userId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception ex) {
            log.error("处理用户注册事件初始化积分账户失败, userId={}", userId, ex);
            try {
                String failKey = "points:init:failed:" + userId;
                redisUtil.set(failKey, "1", 24 * 60 * 60);
            } catch (Exception redisEx) {
                log.error("记录积分初始化失败标记到Redis时出错, userId={}", userId, redisEx);
            }
            channel.basicReject(deliveryTag, false);
        }
    }
}
